/*
 * CFileMediaSink.h
 *
 *  Created on: 2016年1月22日
 *      Author: terry
 */

#ifndef CFILEMEDIASINK_H_
#define CFILEMEDIASINK_H_

#include "FileMediaSink.h"
#include "TCriticalSection.h"
#include "Ffmpeg.h"
#include "FfmpegUtil.h"
#include "TByteBuffer.h"
#include "AudioTranscoder.h"
#include "TThread.h"
#include "PacketQueue.h"
#include "TimePoint.h"


namespace av
{

class CFileMediaSink: public FileMediaSink, comn::Thread
{
public:
	CFileMediaSink();
	virtual ~CFileMediaSink();

    virtual bool open(const char* filename);
    virtual void close();
    virtual bool isOpen();

    virtual void onMediaFormat(const MediaFormat& fmt);

    virtual void onMediaPacket(AVPacketPtr& pkt);

    virtual void onMediaEvent(int event);

    virtual int setFile(const char* filename);

    virtual const char* getFile();

protected:
    virtual int run();
    virtual void doStop();

    void handlePacket(AVPacketPtr& pkt);

protected:
    bool openFile(const char* filename, const MediaFormat& fmt);

    void writeVideo(AVPacketPtr& inPkt);
    void writeAudio(AVPacketPtr& inPkt);
    void doWriteAudio(AVPacket* pkt);

	bool parseVideoProp(AVPacketPtr& pkt);

protected:
    bool openFile();
    void closeFile();
    bool isFileOpen();

	bool isG711(const MediaFormat& fmt);
	bool isMp4(AVFormatContext* fmtCtx);

protected:
    comn::CriticalSection   m_cs;

    MediaFormat m_fmt;

    std::string m_fileName;

    int	m_maxDuration;	/// milliseconds

    int m_videoIndex;
    int m_audioIndex;

    int64_t m_videoStartTime;
    int64_t m_audioStartTime;

    AVFormatContext*	m_fmtCtx;

    bool    m_changeFile;
    AudioTranscoder	m_audioTranscoder;
    bool    m_doAudioTranscode;
    comn::ByteBuffer    m_audioBuffer;

    PacketQueue m_pktQueue;
	int64_t	m_videoPktCount;

	//TimePoint	m_audioInPoint;
	//TimePoint	m_audioPoint;

};


} /* namespace av */

#endif /* CFILEMEDIASINK_H_ */
